package fileServer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import FileServerApplication
import filePackets.DataPacket;

public class TaskServiceThread implements ITaskServiceThread {
	private Integer TaskId;
	private FileTaskContext JobCtx;
	private Thread myThreadHandle;
	private static final String MyString = "FileServerThread";
	byte[] buf = new byte[FileServerApplication.DGRAM_BUF_LEN];
	
	// constructor - starts a new work thread
	public TaskServiceThread(Integer taskId, FileTaskContext jobCtx) {
		TaskId = taskId;
		JobCtx = jobCtx;
		myThreadHandle = new Thread(this);
		myThreadHandle.start();		
	}

	public void run() {
		
		
		DatagramSocket ToClient;
		DatagramPacket UDPPacket = new DatagramPacket(buf, buf.length, JobCtx.getConnInfo().getIP(), JobCtx.getConnInfo().getPort());

		try {
			ToClient = new DatagramSocket();
		} catch (SocketException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		FileInputStream InFile;
		try {
			InFile = new FileInputStream(JobCtx.getFileNumber()+".in");
		} catch (FileNotFoundException e1) {
			FileServerApplication.LogEntry(MyString,"error opening input file");
			e1.printStackTrace();
			return;
		}
				
		boolean done;
		
		do{
			DataPacket OutData = new DataPacket();
			try {
				InFile.read(buf);
			} catch (IOException e) {
				FileServerApplication.LogEntry(MyString,"Error: cannot read from File");
				e.printStackTrace();
				return;
			}
			
			OutData.setBlockData(buf);
			try {
				UDPPacket.setData(OutData.toByteArray());
			} catch (IOException e) {
				FileServerApplication.LogEntry(MyString, "Error converting DataPacket to byte array");
				e.printStackTrace();
				return;
			}
			FileServerApplication.LogEntry(MyString,"sending block number "+JobCtx.getBlockNumber());
			try {
				done = (InFile.available()== 0);
			} catch (IOException e) {
				FileServerApplication.LogEntry(MyString, "Error reading file");
				e.printStackTrace();
				return;
			}
			JobCtx.setBlockNumber(JobCtx.getBlockNumber()+1);
			myCMM.AppUpdateTask()
		}while (!done);

		try {
			InFile.close();
		} catch (IOException e) {
			FileServerApplication.LogEntry(MyString,"Error closing file");
			e.printStackTrace();
			return;
		}
		FileServerApplication.LogEntry(MyString,"Client: done receiving file");
	}
}
